<?php

require_once 'Framework/Controller/Action.php';
require_once 'Framework/File.php';

class EditController extends Framework_Controller_Action
{
    private $_user;
    
    public function init()
    {
        // Если не авторизирован то пшел вон
        if (!$this->_session->get('logged_in')) {
            $this->_redirect('/user/login/');
        }
        
        $this->_user = new User_Self($this->_session->get('user_id'));
        
        $this->_view->friends_count  = $this->_user->getNewFriendsCount();
        $this->_view->messages_count = $this->_user->getNewMessagesCount();
        $this->_view->user_path      = $this->_session->get('user_path');
        $this->_view->user_avatar    = $this->_session->get('user_avatar');
    }
    
    public function indexAction()
    {
        $this->render();
    }
    
    public function photoAction()
    {
        if ($this->_request->getMethod() != 'POST') {
            // Отключаем кеширование
            $this->_response->noCache();
        } elseif($this->_request->del) {
            $this->_user->setAvatar();
            $this->_session->set('user_avatar', '');
            
            $this->_redirect('/edit/photo/');
        } else {
            try {
                $avatar = new Framework_File('photo');
                $type   = $avatar->isImage();
                $path   = $this->_session->get('user_path');
                $filepath     = $this->_request->get('DOCUMENT_ROOT') . $path . '/avatar.' . $type;
                $filepath_min = $this->_request->get('DOCUMENT_ROOT') . $path . '/min/avatar.' . $type;
                $avatar->MoveTo($filepath);
            } catch (Exception $e) {
               $this->_view->error = $e->getMessage();
               $this->render();
            }
            img_resize($filepath, $filepath, 300, 300, 0xFFFFFF, 80);
            img_resize($filepath, $filepath_min, 150, 150, 0xFFFFFF, 80);
            $this->_user->setAvatar('avatar.' . $type);
            
            $this->_session->set('user_avatar', 'avatar.' . $type);
            
            $this->_redirect('/edit/photo/');
        }
        
        $this->render();
    }
}
